<?php

namespace App\Store\Controllers\Financial\Business;

use App\Common\Services\CommonExcelExport;
use App\Store\Models\Order\OrderMaintenance;
use App\Store\Models\Order\OrderSalesRecoveryGoods;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Basic\PaytypeList;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoodsStock;
use App\Store\Models\Order\OrderDeposit;
use App\Store\Models\Order\OrderRecharge;
use App\Store\Models\Order\OrderRecovery;
use App\Store\Models\Order\OrderRecoveryGoods;
use App\Store\Models\Order\OrderSales;
use App\Store\Models\Order\OrderSalesGoods;
use App\Store\Models\Order\OrderSalesSendGoods;
use App\Store\Services\BussinessSummaryExcelExport;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 营业汇总
 */
class SummaryController extends Controller
{

    public function getinfo(Request $request)
    {
        $params = [];
        $params['store_id'] = intval($request->store_id);

        if ($params['store_id'] <= 0) {
            return response()->json(['code' => '001', 'msg' => '请选择门店']);
        }


        $params['classesset_id'] = intval($request->classesset_id);
        $params['goods_brand_id'] = intval($request->goods_brand_id);
        $params['goods_cabinetgroup_id'] = intval($request->goods_cabinetgroup_id);
        $params['order_at_start'] = strtotime($request->order_at_start);
        $params['order_at_end'] = strtotime($request->order_at_end);
        $params['goods_category_id'] = intval($request->goods_category_id);
        $params['goods_style_id'] = intval($request->goods_style_id);
        $params['account_id'] = intval($request->account_id);
        $params['is_sujin'] = intval($request->is_sujin);


        $where1 = [];//销售订单
        $where2 = [];//回收、换货
        $where3 = [];//收款统计
        $where4 = [];//所属门店、班次、时间、导购
        $where_doexport = [];
        // 订单数据类型
        if ($params['store_id'] > 0) {
            $where1[] = ['store_id', $params['store_id']];
            $where2[] = ['store_id', $params['store_id']];
            $where3[] = ['store_id', $params['store_id']];

            $where4[] = ['store_id', $params['store_id']];
            $where_doexport[] = ['store_id', $params['store_id']];
        }

        if ($params['classesset_id'] > 0) {
            $where1[] = ['classesset_id', $params['classesset_id']];
            $where2[] = ['classesset_id', $params['classesset_id']];
            $where3[] = ['classesset_id', $params['classesset_id']];


            $where4[] = ['classesset_id', $params['classesset_id']];
            $where_doexport[] = ['classesset_id', $params['classesset_id']];
        }

        if ($params['goods_brand_id'] > 0) {
            $where1[] = ['goods_brand_id', $params['goods_brand_id']];
            $where2[] = ['id', 0];
            $where3[] = ['goods_brand_id', $params['goods_brand_id']];
            $where4[] = ['id', 0];
        }
        if ($params['goods_cabinetgroup_id'] > 0) {
            $where1[] = ['goods_cabinetgroup_id', $params['goods_cabinetgroup_id']];
            $where3[] = ['goods_cabinetgroup_id', $params['goods_cabinetgroup_id']];
            $where2[] = ['id', 0];
            $where4[] = ['id', 0];
        }

        if ($params['order_at_start'] > 0 && $params['order_at_end'] > $params['order_at_start']) {
            $where1[] = ['order_at', '>=', $params['order_at_start']];
            $where1[] = ['order_at', '<=', $params['order_at_end']];

            $where2[] = ['order_at', '>=', $params['order_at_start']];
            $where2[] = ['order_at', '<=', $params['order_at_end']];

            $where3[] = ['order_at', '>=', $params['order_at_start']];
            $where3[] = ['order_at', '<=', $params['order_at_end']];

            $where4[] = ['order_at', '>=', $params['order_at_start']];
            $where4[] = ['order_at', '<=', $params['order_at_end']];

            $where_doexport[] = ['order_at', '>=', $params['order_at_start']];
            $where_doexport[] = ['order_at', '<=', $params['order_at_end']];
        }

        if ($params['goods_category_id'] > 0) {
            $where1[] = ['goods_category_id', $params['goods_category_id']];
            $where3[] = ['goods_category_id', $params['goods_category_id']];
            $where2[] = ['id', 0];
            $where4[] = ['id', 0];
        }

        if ($params['goods_style_id'] > 0) {
            $where1[] = ['goods_style_id', $params['goods_style_id']];
            $where3[] = ['goods_style_id', $params['goods_style_id']];
            $where2[] = ['id', 0];
            $where4[] = ['id', 0];
        }

        if (in_array($params['is_sujin'], [1, 2])) {
            $where1[] = ['is_sujin', $params['is_sujin']];
            $where2[] = ['is_sujin', $params['is_sujin']];
            $where3[] = ['is_sujin', $params['is_sujin']];
            $where4[] = ['id', 0];
        }


        if ($params['account_id'] > 0) {
            $account_id = $params['account_id'];
            $where1[] = [function ($q) use ($account_id) {
                return $q->where('shopping_account_id1', $account_id)->orWhere('shopping_account_id2', $account_id);
            }];
            $where2[] = [function ($q) use ($account_id) {
                return $q->where('shopping_account_id1', $account_id)->orWhere('shopping_account_id2', $account_id);
            }];
            $where3[] = [function ($q) use ($account_id) {
                return $q->where('shopping_account_id1', $account_id)->orWhere('shopping_account_id2', $account_id);
            }];
            $where4[] = [function ($q) use ($account_id) {
                return $q->where('shopping_account_id1', $account_id)->orWhere('shopping_account_id2', $account_id);
            }];

            $where_doexport[] = [function ($q) use ($account_id) {
                return $q->where('shopping_account_id1', $account_id)->orWhere('shopping_account_id2', $account_id);
            }];
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);

        $cp_id = $accountinfo['cp_id'];
        $store_ids = StoreCommon::getCurrentAccountStoreId($request);


        $paymoneysummary = $this->getpaymoneysummary($where3, $where4, $cp_id, $store_ids, $accountinfo, $request);
        $salessummaryinfo = $this->getsalessummary($where1, $cp_id, $store_ids, $params['store_id'], $accountinfo, $request);
        $salessummary = $salessummaryinfo['goods_category_list'];
        $salsegoodslist = $salessummaryinfo['salsegoodslist'];
        $sendgoodssummary = $this->getsendgoodssummary($where4, $cp_id, $store_ids, $accountinfo, $request);
        $recoverysummary = $this->getrecoverysummary($where2, $cp_id, $store_ids, $accountinfo, $request);
        $orderinfo = $this->orderinfoexport($where1, $where2, $where_doexport, $cp_id, $store_ids, $accountinfo, $request);

        foreach ($orderinfo as $key => &$vv) {
            if ($vv['type'] == 'nomal') {
                $vv['fee'] = is_numeric($vv['fee']) ? $vv['fee'] / 100 : '';
                $vv['total_money'] = is_numeric($vv['total_money']) ? $vv['total_money'] / 100 : '';
                $vv['real_total_money'] = is_numeric($vv['real_total_money']) ? $vv['real_total_money'] / 100 : '';
            }

        }

        if ($request->isdoexport == 1) {
            return $this->doexport($paymoneysummary, $salessummary, $sendgoodssummary, $recoverysummary, $orderinfo, $request, $params['store_id']);
        }

        if ($request->isdoexport == 2) {
            return $this->doexportinfo($orderinfo, $params['store_id']);
        }


        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => compact('paymoneysummary', 'salessummary', 'sendgoodssummary', 'recoverysummary', 'salsegoodslist', 'orderinfo')]);


    }

    protected function doexportinfo($orderinfo, $store_id)
    {

        $store_name = SiteStore::where(['id' => $store_id])->value('store_name');
        $row = [
            ['goods_sn_code' => '营业汇总表（明细）'],
            ['goods_sn_code' => '所属门店：' . $store_name],
            [
                'order_sn' => '订单号',
                'goods_sn_code' => '商品条码',
                'goods_name' => '商品名称',
                'goods_category_name' => '商品类别',
                'count' => '数量',
                'weight_old' => '重量',
                'weight' => '实重',
                'fee' => '工费',
                'total_money' => '销售金额',
                'discount' => '折扣',
                'real_total_money' => '实收金额',
                'pay_type_name' => '支付方式',
                'order_type' => '订单类型',
                'order_at' => '销售日期',
                'shoppingaccountinfo1' => '导购',
                'real_name' => '会员姓名',
                'mobile' => '电话',
            ]];

        $data5 = $orderinfo;


        $filename = '营业汇总表明细导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $data5, []), $filename);
    }

    protected function doexport($paymoneysummary, $salessummary, $sendgoodssummary, $recoverysummary, $orderinfo, $request, $store_id)
    {
        //dd($paymoneysummary);
        $store_name = SiteStore::where(['id' => $store_id])->value('store_name');
        $row1 = [];
        $data1 = [];
        //return compact('sum_total_money','sum_real_total_money_with_balance','sum_coupon_money','paytype','sum_recharge_money','sum_deposit_money');
        $row1_data = [];
        $data1_data = [];
        $title = [];
        $title_store = [];
        foreach ($paymoneysummary['paytype'] as $val) {
            if (!$title) {
                $title = [$val['paytype_name'] => '营业汇总表'];

                $title_store = [$val['paytype_name'] => '所属门店：' . $store_name];
            }
            $row1_data[$val['paytype_name']] = $val['paytype_name'];
            $data1_data[$val['paytype_name']] = $val['total_money'] / 100;
        }
        $row1_data['sum_real_total_money_with_balance'] = '实收金额';
        $data1_data['sum_real_total_money_with_balance'] = $paymoneysummary['sum_real_total_money_with_balance'] / 100;
        $row1_data['sum_total_money'] = '销售金额';
        $data1_data['sum_total_money'] = $paymoneysummary['sum_total_money'] / 100;
        $row1_data['sum_recharge_money'] = '充值金额';
        $data1_data['sum_recharge_money'] = $paymoneysummary['sum_recharge_money'] / 100;
        $row1_data['sum_deposit_money'] = '定金金额';
        $data1_data['sum_deposit_money'] = $paymoneysummary['sum_deposit_money'] / 100;
        $row1_data['sum_coupon_money'] = '抵扣金额';
        $data1_data['sum_coupon_money'] = $paymoneysummary['sum_coupon_money'] / 100;

        $row1_data['sum_balance_money'] = '使用预存';
        $data1_data['sum_balance_money'] = $paymoneysummary['sum_balance_money'] / 100;

        $row1[] = $title;
        $row1[] = $title_store;
        $row1[] = $row1_data;

        $data1[] = $data1_data;

        $is_store_account = StoreCommon::getIsStoreAccount($request);

        $row2 = [[
            'strore_name' => '所属门店',
            'goods_category_name' => '商品类别',
            'count' => '数量',
            'weight' => '重量',
            'total_cost_price' => '总金额',
            'label_price' => '商品标价',
            'total_money' => '销售金额',
            'dold_fee' => '折旧费',
            'recovery_goods_meony' => '回收金额',
            // 'real_total_money_with_balance' => '实收金额',
            'real_total_money' => '实收金额',
            'cost_fee' => '成本金额',
        ]];


        if ($is_store_account != true) {
            unset($row2[0]['cost_fee']);
        }


        foreach ($salessummary as &$vv) {
            $vv['total_cost_price'] = $vv['total_cost_price'] / 100;
            $vv['label_price'] = $vv['label_price'] / 100;
            $vv['total_money'] = $vv['total_money'] / 100;
            $vv['dold_fee'] = $vv['dold_fee'] / 100;
            $vv['recovery_goods_meony'] = $vv['recovery_goods_meony'] / 100;
            // $vv['real_total_money_with_balance'] = $vv['real_total_money_with_balance'] / 100;
            $vv['real_total_money'] = $vv['real_total_money'] / 100;
            if ($is_store_account != true) {
                $vv['cost_fee'] = '';

            } else {
                $vv['cost_fee'] = $vv['cost_fee'] / 100;
            }
        }

        $data2 = $salessummary;
//        $data2[]=[
//            'strore_name'=>'合计',
//            'goods_category_name'=>'',
//            'count'=>array_sum(array_column($salessummary,'count')),
//            'weight'=>array_sum(array_column($salessummary,'weight')),
//            'total_cost_price'=>array_sum(array_column($salessummary,'total_cost_price')),
//            'label_price'=>array_sum(array_column($salessummary,'label_price')),
//            'total_money'=>array_sum(array_column($salessummary,'total_money')),
//            'dold_fee'=>array_sum(array_column($salessummary,'dold_fee')),
//            'recovery_goods_meony'=>array_sum(array_column($salessummary,'recovery_goods_meony')),
//            'real_total_money_with_balance'=>array_sum(array_column($salessummary,'real_total_money_with_balance')),
//            'cost_fee'=>array_sum(array_column($salessummary,'cost_fee')),
//        ];

        //getrecoverysummary

        $row3 = [[

            'recovery_type' => '回收方式',
            'recovery_count' => '件数',
            'recovery_weight' => '重量',
            'recovery_d_price' => '旧料标价',
            'recovery_money' => '回收金额',

            'slaserecovery_type' => '回收方式',
            'slaserecovery_count' => '件数',
            'slaserecovery_weight' => '重量',
            'slaserecovery_d_price' => '旧料标价',
            'slaserecovery_money' => '回收金额',
        ]];
        $slaserecovery_type1 = $recoverysummary['slaserecovery_type1'];
        $recovery_type1 = $recoverysummary['recovery_type1'];
        $slaserecovery_type2 = $recoverysummary['slaserecovery_type2'];
        $recovery_type2 = $recoverysummary['recovery_type2'];
        $data3 = [
            [
                'recovery_type' => '按克',
                'recovery_count' => $recovery_type1['count'],
                'recovery_weight' => $recovery_type1['weight'],
                'recovery_d_price' => $recovery_type1['d_price'] / 100,
                'recovery_money' => $recovery_type1['money'] / 100,

                'slaserecovery_type' => '按克',
                'slaserecovery_count' => $slaserecovery_type1['count'],
                'slaserecovery_weight' => $slaserecovery_type1['weight'],
                'slaserecovery_d_price' => $slaserecovery_type1['d_price'] / 100,
                'slaserecovery_money' => $slaserecovery_type1['money'] / 100,

            ],
            [

                'recovery_type' => '标价',
                'recovery_count' => $recovery_type2['count'],
                'recovery_weight' => $recovery_type2['weight'],
                'recovery_d_price' => $recovery_type2['d_price'] / 100,
                'recovery_money' => $recovery_type2['money'] / 100,

                'slaserecovery_type' => '标价',
                'slaserecovery_count' => $slaserecovery_type2['count'],
                'slaserecovery_weight' => $slaserecovery_type2['weight'],
                'slaserecovery_d_price' => $slaserecovery_type2['d_price'] / 100,
                'slaserecovery_money' => $slaserecovery_type2['money'] / 100,


            ]
        ];

        //getsendgoodssummary
        $row4 = [[
            'id' => '序号',
            'sendgoods_name' => '品名',
            'count' => '数量',
            'piecepricetotal' => '成本金额',
        ]];

        if (!$is_store_account) {
            unset($row4[0]['piecepricetotal']);
        }
        $data4 = [];
        foreach ($sendgoodssummary as $key => $vvv) {
            $data4[] = [
                'id' => $key + 1,
                'sendgoods_name' => $vvv['sendgoods_name'],
                'count' => $vvv['count'],
                'piecepricetotal' => $vvv['piecepricetotal'] / 100
            ];
        }

        // $row5=[[
        //     'goods_sn_code'=>'商品条码',
        //     'goods_name'=>'商品名称',
        //     'goods_category_name'=>'商品类别',
        //     'count'=>'数量',
        //     'weight_old'=>'重量',
        //     'weight'=>'实重',
        //     'fee'=>'工费',
        //     'total_money'=>'销售金额',
        //     'discount'=>'折扣',
        //     'real_total_money'=>'实收金额',
        //     'order_type'=>'订单类型'
        // ]];
        // // foreach($orderinfo as $key=>&$vv){
        // //     if($vv['type']=='nomal'){
        // //         $vv['fee']=is_numeric($vv['fee'])?$vv['fee']/100:'';
        // //         $vv['total_money']=is_numeric($vv['total_money'])?$vv['total_money']/100:'';
        // //         $vv['real_total_money']=is_numeric($vv['real_total_money'])?$vv['real_total_money']/100:'';
        // //     }

        // // }

        // $data5=$orderinfo;
        $row5 = [];
        $data5 = [];


        $datawith = [
            'A' => '18', 'B' => '18', 'C' => '18', 'D' => '20', 'E' => '18', 'F' => '18', 'G' => '18', 'H' => '18', 'I' => '18', 'J' => '18', 'K' => '18', 'L' => '18', 'M' => '18'
        ];
        $filename = '营业汇总导出_' . time() . '.xlsx';

        return Excel::download(new BussinessSummaryExcelExport($row1, $data1, $row2, $data2, $row3, $data3, $row4, $data4, $row5, $data5, $datawith), $filename);


    }


    protected function orderinfoexport($where1, $where2, $where_doexport, $cp_id, $store_ids, $accountinfo, $request)
    {
        if ($accountinfo['type'] == 11) {
            $training = StoreCommon::gettraining($request);
            if ($training['training_min'] == 0 && $training['training_max'] == 0) {
                return response()->json(['code' => '001', 'msg' => '培训账号，请先设置公司培训上下限']);
            }
        }

        if ($accountinfo['type'] == 11) {
            $sales_recovery_where = $where2 + [
                    ['money', '>', $training['training_min']],
                    ['money', '<', $training['training_max']],
                ];
        } else {
            $sales_recovery_where = $where2;
        }

        if ($accountinfo['type'] == 11) {
            $recovery_where = $where2 + [
                    ['money', '>', $training['training_min']],
                    ['money', '<', $training['training_max']],
                ];
        } else {
            $recovery_where = $where2;
        }

        if ($accountinfo['type'] == 11) {
            $sales_where = $where1 + [
                    ['total_money', '>', $training['training_min']],
                    ['total_money', '<', $training['training_max']],
                ];
        } else {
            $sales_where = $where1;
        }

        $saleorder = OrderSales::where(['cp_id' => $cp_id])->where($where_doexport)
            ->where(function ($query) use ($store_ids) {
                if ($store_ids) {//权限控制
                    if (is_array($store_ids)) {//获取当前权限下的门店
                        $query->whereIn('store_id', $store_ids);
                    }
                    if (is_numeric($store_ids) && intval($store_ids) > 0) {//获取当前门店下的列表
                        $query->where('store_id', intval($store_ids));
                    }
                }
            })->where(['is_del' => 1])->where('audit_status', '<>', 3)->with([
                'goodslist' => function ($query) use ($sales_where) {
                    $query->where($sales_where);
                },
                'recoverygoodslist' => function ($query) use ($sales_recovery_where) {
                    $query->where($sales_recovery_where);
                }, 'recoverygoodslist.goods_category', 'memberinfo', 'shoppingaccountinfo1'])->get()->toArray();

        $recoveryorder = OrderRecovery::where(['cp_id' => $cp_id])->where($where_doexport)
            ->where(function ($query) use ($store_ids) {
                if ($store_ids) {//权限控制
                    if (is_array($store_ids)) {//获取当前权限下的门店
                        $query->whereIn('store_id', $store_ids);
                    }
                    if (is_numeric($store_ids) && intval($store_ids) > 0) {//获取当前门店下的列表
                        $query->where('store_id', intval($store_ids));
                    }
                }
            })->where(['is_del' => 1])->where('audit_status', '<>', 3)->with([
                'goodslist' => function ($query) use ($recovery_where) {
                    $query->where($recovery_where);
                }, 'goodslist.goods_category', 'memberinfo', 'shoppingaccountinfo1'])->get()->toArray();


        $list_array_merge = array_merge($saleorder, $recoveryorder);

        usort($list_array_merge, function ($a, $b) {
            return $a['order_at'] > $b['order_at'];
        });
        $list = [];
        // print_r($list_array_merge);exit;

        foreach ($list_array_merge as $val) {
            if (isset($val['recoverygoodslist'])) {

                if (count($val['goodslist']) == 0 && count($val['recoverygoodslist']) == 0) {
                    continue;
                }

                foreach ($val['goodslist'] as $goods) {
                    $goodsinfo = json_decode($goods['goodsinfo'], true);
                    $item = [
                        'order_sn' => $val['order_sn'],
                        'goods_sn_code' => $goods['goods_sn_code'],
                        'goods_name' => $goodsinfo['goods_name'],
                        'goods_category_name' => $goodsinfo['goods_category']['category_name'],
                        'count' => $goods['count'],
                        'weight_old' => $goodsinfo['goods_category']['is_gram'] == 1 ? $goods['weight_old'] : $goods['weight'],
                        'weight' => $goods['weight'],
                        'fee' => $goodsinfo['goods_category']['is_gram'] == 1 ? (intval($goods['weight'] * ($goods['cost_price'] - $goods['cost_price_discount'])) + intval($goods['count'] * $goods['pieceprice_fee'])) : 0,
                        'total_money' => $goods['total_money'],
                        'discount' => $goods['discount'] > 0 ? $goods['discount'] : '',
                        'real_total_money' => $goods['real_total_money'],
                        'pay_type_name' =>  $val['pay_type_name'],
                        'order_type' => '销售开单',
                        'type' => 'nomal',
                        'order_at' =>  date('Y-m-d H:i', $val['order_at']),
                        'shoppingaccountinfo1' => $val['shoppingaccountinfo1']['real_name'],
                        'real_name' => $val['memberinfo'] ?  $val['memberinfo']['real_name'] : '',
                        'mobile' => $val['memberinfo'] ?  $val['memberinfo']['mobile'] : '',
                    ];
                    $list[] = $item;
                }

                foreach ($val['recoverygoodslist'] as $goods) {
                    $item = [
                        'order_sn' => $val['order_sn'],
                        'goods_sn_code' => $goods['goods_sn_code'],
                        'goods_name' => '',
                        'goods_category_name' => $goods['goods_category']['category_name'],
                        'count' => $goods['count'],
                        'weight' => $goods['weight'],
                        'weight_old' => $goods['weight'] - $goods['loss_weight'],
                        'fee' => '',
                        'total_money' => '',
                        'discount' => $goods['discount'] > 0 ? $goods['discount'] : '',
                        'real_total_money' => $goods['money'],
                        'pay_type_name' =>  $val['pay_type_name'],
                        'order_type' => $goods['change_type'] == 1 ? '换货回收' : '换货上柜',
                        'type' => 'nomal',
                        'order_at' =>  date('Y-m-d H:i', $val['order_at']),
                        'shoppingaccountinfo1' => $val['shoppingaccountinfo1']['real_name'],
                        'real_name' => $val['memberinfo'] ?  $val['memberinfo']['real_name'] : '',
                        'mobile' => $val['memberinfo'] ?  $val['memberinfo']['mobile'] : '',
                    ];
                    $list[] = $item;
                }

            } else {
                if (count($val['goodslist']) == 0) {
                    continue;
                }

                foreach ($val['goodslist'] as $goods) {
                    $item = [
                        'order_sn' => $val['order_sn'],
                        'goods_sn_code' => $goods['goods_sn_code'],
                        'goods_name' => '',
                        'goods_category_name' => $goods['goods_category']['category_name'],
                        'count' => $goods['count'],
                        'weight' => $goods['weight'],
                        'weight_old' => $goods['weight'] - $goods['loss_weight'],
                        'fee' => '',
                        'total_money' => '',
                        'discount' => $goods['discount'] > 0 ? $goods['discount'] : '',
                        'real_total_money' => $goods['money'],
                        'pay_type_name' =>  $val['pay_type_name'],
                        'order_type' => $goods['change_type'] == 1 ? '纯回收' : '纯回收上柜',
                        'type' => 'nomal',
                        'order_at' =>  date('Y-m-d H:i', $val['order_at']),
                        'shoppingaccountinfo1' => $val['shoppingaccountinfo1']['real_name'],
                        'real_name' => $val['memberinfo'] ?  $val['memberinfo']['real_name'] : '',
                        'mobile' => $val['memberinfo'] ?  $val['memberinfo']['mobile'] : '',
                    ];
                    $list[] = $item;
                }
            }


        }

        return $list;
    }


    protected function getrecoverysummary($where2, $cp_id, $store_ids, $accountinfo, $request)
    {
        if ($accountinfo['type'] == 11) {
            $training = StoreCommon::gettraining($request);
            if ($training['training_min'] == 0 && $training['training_max'] == 0) {
                return response()->json(['code' => '001', 'msg' => '培训账号，请先设置公司培训上下限']);
            }
        }

        if ($accountinfo['type'] == 11) {
            $sales_recovery_where = $where2 + [
                    ['money', '>', $training['training_min']],
                    ['money', '<', $training['training_max']],
                ];
            $recovery_where = $where2 + [
                    ['money', '>', $training['training_min']],
                    ['money', '<', $training['training_max']],
                ];
        } else {
            $sales_recovery_where = $where2;
            $recovery_where = $where2;
        }

        $slaserecovery_type1 = OrderSalesRecoveryGoods::query()
            ->where(['cp_id' => $cp_id])
            ->where($sales_recovery_where)
            ->where(['is_del' => 1])
            ->where('audit_status', '<>', 3)
            ->when(!empty($store_ids), function ($query) use ($store_ids) {
                if (is_array($store_ids)) {
                    $query->whereIn('store_id', $store_ids);
                } else {
                    $query->where('store_id', intval($store_ids));
                }

            })
            ->where('recovery_type', 1)
            ->select([DB::raw('IFNULL(sum(count),0) as count'), DB::raw('IFNULL(sum(weight*count),0) as weight'), DB::raw('IFNULL(sum(d_price),0) as d_price'), DB::raw('IFNULL(sum(money),0) as money')])
            ->first()
            ->toArray();


        $slaserecovery_type2 = OrderSalesRecoveryGoods::query()
            ->where(['cp_id' => $cp_id])
            ->where($sales_recovery_where)
            ->where(['is_del' => 1])
            ->where('audit_status', '<>', 3)
            ->when(!empty($store_ids), function ($query) use ($store_ids) {
                if (is_array($store_ids)) {
                    $query->whereIn('store_id', $store_ids);
                } else {
                    $query->where('store_id', intval($store_ids));
                }

            })
            ->where('recovery_type', 2)
            ->select([DB::raw('IFNULL(sum(count),0) as count'), DB::raw('IFNULL(sum(weight*count),0) as weight'), DB::raw('IFNULL(sum(d_price),0) as d_price'), DB::raw('IFNULL(sum(money),0) as money')])
            ->first()
            ->toArray();
        $recovery_type1 = OrderRecoveryGoods::where(['cp_id' => $cp_id])
            ->where($recovery_where)->where(['is_del' => 1])
            ->where('audit_status', '<>', 3)
            ->when(!empty($store_ids), function ($query) use ($store_ids) {
                if (is_array($store_ids)) {
                    $query->whereIn('store_id', $store_ids);
                } else {
                    $query->where('store_id', intval($store_ids));
                }

            })
            ->where('recovery_type', 1)
            ->select([DB::raw('IFNULL(sum(count),0) as count'), DB::raw('IFNULL(sum(weight*count),0) as weight'), DB::raw('IFNULL(sum(d_price),0) as d_price'), DB::raw('IFNULL(sum(money),0) as money')])
            ->first()
            ->toArray();
        $recovery_type2 = OrderRecoveryGoods::where(['cp_id' => $cp_id])
            ->where($recovery_where)->where(['is_del' => 1])
            ->where('audit_status', '<>', 3)
            ->when(!empty($store_ids), function ($query) use ($store_ids) {
                if (is_array($store_ids)) {
                    $query->whereIn('store_id', $store_ids);
                } else {
                    $query->where('store_id', intval($store_ids));
                }

            })->where('recovery_type', 2)
            ->select([DB::raw('IFNULL(sum(count),0) as count'), DB::raw('IFNULL(sum(weight*count),0) as weight'), DB::raw('IFNULL(sum(d_price),0) as d_price'), DB::raw('IFNULL(sum(money),0) as money')])
            ->first()
            ->toArray();

        return compact('slaserecovery_type1', 'slaserecovery_type2', 'recovery_type1', 'recovery_type2');


    }


    protected function getsalessummary($where1, $cp_id, $store_ids, $store_id, $accountinfo, $request)
    {
        if ($accountinfo['type'] == 11) {
            $training = StoreCommon::gettraining($request);
            if ($training['training_min'] == 0 && $training['training_max'] == 0) {
                return response()->json(['code' => '001', 'msg' => '培训账号，请先设置公司培训上下限']);
            }
        }

        if ($accountinfo['type'] == 11) {
            $sales_where = $where1 + [
                    ['total_money', '>', $training['training_min']],
                    ['total_money', '<', $training['training_max']],
                ];
        } else {
            $sales_where = $where1;
        }
        $query = OrderSalesGoods::where(['cp_id' => $cp_id])->where($sales_where)->where(['red_status' => 1, 'is_del' => 1])->where('audit_status', '<>', 3);
        $querybasic = $query;
        if ($store_ids) {//权限控制
            if (is_array($store_ids)) {//获取当前权限下的门店
                $query->whereIn('store_id', $store_ids);
            }
            if (is_numeric($store_ids) && intval($store_ids) > 0) {//获取当前门店下的列表
                $query->where('store_id', intval($store_ids));
            }
        }
        $strore_name = SiteStore::where(['id' => $store_id])->value('store_name');
        // $goods_category_list=$query->groupBy('goods_category_id')
        // ->select(['goods_category_id','store_id'])->get()->toArray();
        // foreach($goods_category_list as &$val){
        //     $val['strore_name']=$strore_name;
        //     $val['goods_category_name']=GoodsCategory::where(['id'=>$val['goods_category_id']])->value('category_name');
        //     $vquery=$querybasic;
        //     $val['count']=$vquery->where('goods_category_id',$val['goods_category_id'])->sum('count');
        //     $val['weight']=$vquery->where('goods_category_id',$val['goods_category_id'])->sum('weight');
        //     //总金额--总工费
        //     $val['total_cost_price']=$vquery->where('goods_category_id',$val['goods_category_id'])->sum(DB::raw('(cost_price-cost_price_discount)* weight'));

        //     $val['label_price']=$vquery->where('goods_category_id',$val['goods_category_id'])->sum('label_price');
        //     //销售金额
        //     $val['total_money']=$vquery->where('goods_category_id',$val['goods_category_id'])->sum('total_money');
        //     $val['dold_fee']=$vquery->where('goods_category_id',$val['goods_category_id'])->sum('sub_dold_fee');
        //     $val['recovery_goods_meony']=$vquery->where('goods_category_id',$val['goods_category_id'])->sum('sub_recovery_goods_meony');
        //     $val['real_total_money_with_balance']=$vquery->where('goods_category_id',$val['goods_category_id'])->sum('real_total_money_with_balance');
        //     $val['cost_fee']=$vquery->where('goods_category_id',$val['goods_category_id'])->sum('cost_fee');
        // }

        $salsegoodslist = $query->with(['memberinfo', 'storeinfo', 'orderinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'memberinfo.storeinfo'])->get()->toArray();


        $goods_category_list = $query->groupBy('goods_category_id')
            ->select(['goods_category_id', DB::raw("sum(count) as count"), DB::raw("sum(weight) as weight"), DB::raw("sum('(cost_price-cost_price_discount)* weight + (pieceprice_fee*count)') as total_cost_price"),
                DB::raw("sum(label_price) as label_price"), DB::raw("sum(total_money) as total_money"), DB::raw("sum(sub_dold_fee) as dold_fee"),
                DB::raw("sum(sub_recovery_goods_meony) as recovery_goods_meony"), DB::raw("sum(real_total_money_with_balance) as real_total_money_with_balance"),
                DB::raw("sum(cost_fee) as cost_fee"), DB::raw("sum(real_total_money) as real_total_money")])->get()->toArray();


        foreach ($goods_category_list as &$val) {
            $val['strore_name'] = $strore_name;
            $val['goods_category_name'] = GoodsCategory::where(['id' => $val['goods_category_id']])->value('category_name');
            $val['recovery_goods_meony'] = $val['recovery_goods_meony'] > 0 ? -$val['recovery_goods_meony'] : 0;
        }

        return compact('goods_category_list', 'salsegoodslist');


    }

    protected function getpaymoneysummary($where3, $where4, $cp_id, $store_ids, $accountinfo, $request)
    {
        $store_ids = (is_array($store_ids) && !empty($store_ids)) ? $store_ids : (intval($store_ids) > 0 ? [$store_ids] : []);
        if ($accountinfo['type'] == 11) {
            $training = StoreCommon::gettraining($request);
            if ($training['training_min'] == 0 && $training['training_max'] == 0) {
                return response()->json(['code' => '001', 'msg' => '培训账号，请先设置公司培训上下限']);
            }
        }

        if ($accountinfo['type'] == 11) {
            $sales_where = $where3 + [
                    ['total_money', '>', $training['training_min']],
                    ['total_money', '<', $training['training_max']],
                ];
        } else {
            $sales_where = $where3;
        }

        $salesToalMoney = 0;
        $salesRalMoney = 0;
        if (!empty($sales_where)) {
            $salesPIds = OrderSalesGoods::query()->where(['cp_id' => $cp_id])->where($sales_where)
                ->where(['red_status' => 1, 'is_del' => 1])
                ->where('audit_status', '<>', 3)
                ->get()
                ->pluck('pid')
                ->toArray();
            // 开单
            $orderSales = OrderSales::query()
                ->where(['cp_id' => $cp_id])->whereIn('id', $salesPIds)
                ->where(['red_status' => 1, 'is_del' => 1])
                ->where('audit_status', '<>', 3)
                ->when(!empty($store_ids), function ($query) use ($store_ids) {
                    $query->whereIn('store_id', $store_ids);
                })
                ->get(['real_money', 'total_money', 'pay_type_id', 'mixed_payment','pay_money'])
                ->toArray();

            $salesToalMoney = array_column($orderSales, 'total_money');
            $salesToalMoney = array_sum($salesToalMoney);
            //$salesRalMoney = array_column($orderSales, 'real_money');
            $salesRalMoney = array_column($orderSales, 'pay_money');
            $salesRalMoney = array_sum($salesRalMoney);

        }


        if ($accountinfo['type'] == 11) {
            $recharge_where = $where4 + [
                    ['money', '>', $training['training_min']],
                    ['money', '<', $training['training_max']],
                ];
        } else {
            $recharge_where = $where4;
        }

        // 充值开单
        $recharge = OrderRecharge::query()
            ->where($recharge_where)->where(['is_del' => 1])
            ->where('audit_status', '<>', 3)
            ->when(!empty($store_ids), function ($query) use ($store_ids) {
                $query->whereIn('store_id', $store_ids);
            })
            ->selectRaw('money as real_money,pay_type_id,mixed_payment')
            ->get()
            ->toArray();

        $rechargeMoney = array_column($recharge, 'real_money');
        $sum_recharge_money = array_sum($rechargeMoney);


        if ($accountinfo['type'] == 11) {
            $deposit_where = $where4 + [
                    ['money', '>', $training['training_min']],
                    ['money', '<', $training['training_max']],
                ];
        } else {
            $deposit_where = $where4;
        }
        // 定金
        $deposit = OrderDeposit::where($deposit_where)
            ->where(['is_del' => 1])
            ->where('audit_status', '<>', 3)
            ->when(!empty($store_ids), function ($query) use ($store_ids) {
                $query->whereIn('store_id', $store_ids);
            })
            ->selectRaw('money as real_money,pay_type_id,mixed_payment')
            ->get()
            ->toArray();

        $depositMoney = array_column($deposit, 'real_money');
        $sum_deposit_money = array_sum($depositMoney);


        //  维修开单
        $maintenance = OrderMaintenance::query()->where(['cp_id' => $cp_id, 'is_del' => 1])->where('audit_status', '<>', 3)
            ->where($deposit_where)
            ->when(!empty($store_ids), function ($query) use ($store_ids) {
                $query->whereIn('store_id', $store_ids);
            })
            ->selectRaw('money as real_money,pay_type_id,mixed_payment')
            ->get()
            ->toArray();

        $maintenanceMmoney = array_column($maintenance, 'real_money');
        $maintenanceMmoney = array_sum($maintenanceMmoney);


        $goods_category_id = $request->goods_category_id;
        $recovery_pids = [];
        if (!empty($goods_category_id)) {
            $recovery_pids = OrderRecoveryGoods::query()
                ->where(['cp_id' => $cp_id, 'is_del' => 1])
                ->where($deposit_where)
                ->where('goods_category_id', $goods_category_id)
                ->get()
                ->pluck('pid')
                ->toArray();
        }

        // 查询纯回收金额

        $recovery = OrderRecovery::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->where('audit_status', '<>', 3)
            ->where($deposit_where)
            ->when(!empty($goods_category_id), function ($query) use ($recovery_pids) {
                $query->whereIn('id', $recovery_pids);
            })
            ->selectRaw('total_money as real_money,pay_type_id,mixed_payment')
            ->get()
            ->toArray();

        // 纯回收处理为负数
        foreach ($recovery as &$item) {
            $item['real_money'] = -abs($item['real_money']);
            if (!empty($item['mixed_payment'])) {
                foreach ($item['mixed_payment'] as &$pay) {
                    $pay = -abs($pay);
                }
            }
        }

        $recoveryMmoney = array_column($recovery, 'real_money');
        $recoveryMmoney = array_sum($recoveryMmoney);

        // 应收金额
        $sum_total_money = $salesToalMoney + $sum_recharge_money + $sum_deposit_money + $maintenanceMmoney + $recoveryMmoney;

        // 实际金额
        $sum_real_total_money_with_balance = $salesRalMoney + $sum_recharge_money + $sum_deposit_money + $maintenanceMmoney + $recoveryMmoney;

        // 优惠券和余额累计
        $salesGoods = OrderSalesGoods::query()->where(['cp_id' => $cp_id])
            ->where($sales_where)->where(['red_status' => 1, 'is_del' => 1])
            ->where('audit_status', '<>', 3)
            ->when(!empty($store_ids), function ($query) use ($store_ids) {
                $query->whereIn('store_id', $store_ids);
            })
            ->selectRaw('sum(sub_coupon_money) as sub_coupon_money,sum(sub_balance_money) as sub_balance_money,sum(sub_pointstobalance) as sub_pointstobalance')
            ->first();

        $salesGoods = empty($salesGoods) ? [] : $salesGoods->toArray();
        $sum_coupon_money = $salesGoods['sub_coupon_money'] ?? 0;
        $sum_balance_money = $salesGoods['sub_balance_money'] ?? 0;
        $sub_pointstobalance = $salesGoods['sub_pointstobalance'] ?? 0;

        $sum_balance_money = $sum_balance_money + $sub_pointstobalance;


        $orderSales = array_values(array_merge($orderSales, $recharge, $deposit, $maintenance, $recovery));

        $payMoneyArr = [];
        foreach ($orderSales as $order) {
            if (empty($order['mixed_payment'])) {
                $payMoneyArr[$order['pay_type_id']][] = $order['real_money'] ?? 0;
            } else {
                foreach ($order['mixed_payment'] as $key => $money) {
                    $ks = explode('_', $key)[1] ?? 0;
                    if ($ks > 0 && $money != 0) {
                        $payMoneyArr[$ks][] = $money;
                    }
                }
            }
        }

        $paytype = PaytypeList::where(['cp_id' => $cp_id, 'is_del' => 1])
            ->get()
            ->toArray();

        foreach ($paytype as &$type) {
            $type['total_money'] = empty($payMoneyArr[$type['id']]) ? 0 : array_sum($payMoneyArr[$type['id']]);
        }

        return compact('sum_total_money', 'sum_real_total_money_with_balance', 'sum_coupon_money', 'paytype', 'sum_recharge_money', 'sum_deposit_money', 'sum_balance_money');

    }

    protected function getsendgoodssummary($where4, $cp_id, $store_ids, $accountinfo, $request)
    {
        if ($accountinfo['type'] == 11) {
            $training = StoreCommon::gettraining($request);
            if ($training['training_min'] == 0 && $training['training_max'] == 0) {
                return response()->json(['code' => '001', 'msg' => '培训账号，请先设置公司培训上下限']);
            }
        }

//        if ($accountinfo['type'] == 11) {
//            $sales_where = $where4 + [
//                ['total_money', '>', $training['training_min']],
//                ['total_money', '<', $training['training_max']],
//            ];
//        } else {
//            $sales_where = $where4;
//        }
        $query = OrderSalesSendGoods::where(['cp_id' => $cp_id])->where($where4)->where(['is_del' => 1])->where('audit_status', '<>', 3);
        $querybasic = $query;
        if ($store_ids) {//权限控制
            if (is_array($store_ids)) {//获取当前权限下的门店
                $query->whereIn('store_id', $store_ids);
            }
            if (is_numeric($store_ids) && intval($store_ids) > 0) {//获取当前门店下的列表
                $query->where('store_id', intval($store_ids));
            }
        }


        $list = $query->groupBy('send_goods_stock_id')->select(['send_goods_stock_id', 'store_id', DB::raw('IFNULL(sum(count),0) as count')])->get()->toArray();


        foreach ($list as &$sval) {
            $info = GoodsSendgoodsStock::where(['id' => $sval['send_goods_stock_id']])->first();
            $sval['sendgoods_name'] = $info->sendgoods_name;
            // $vquery=$querybasic;
            // $sval['count']=$vquery->where(['send_goods_stock_id'=>$sval['send_goods_stock_id']])->sum('count');
            $sval['piecepricetotal'] = $info['pieceprice'] * $sval['count'];
        }

        return $list;


    }

}
